<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:prod:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:prod:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:prod:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:prod:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="prodList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="prodId" />
      <el-table-column label="SPU" align="center" prop="prodSpu" />
      <el-table-column label="商品类型" align="center" prop="prodKind">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_product_kind"
            :value="scope.row.prodKind"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="typeName" />
      <el-table-column label="状态" align="center" prop="prodStatus">
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.prodStatus == 0">草稿</el-tag>
          <el-tag type="success" v-if="scope.row.prodStatus == 1">上架</el-tag>
          <el-tag v-if="scope.row.prodStatus == 2">下架</el-tag>
          <el-tag type="售罄" v-if="scope.row.prodStatus == 3">售罄</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="prodName">
        <template slot-scope="scope">
          <span v-html="scope.row.prodName"></span>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="brandName" />
      <el-table-column label="商品单位" align="center" prop="unitId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_product_unit"
            :value="scope.row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品标签" align="center" prop="tagId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_product_tag"
            :value="scope.row.tagId"
          />
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="appr" />
      <el-table-column
        label="缩略图"
        align="center"
        prop="prodImage"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.prodImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:prod:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:prod:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddAtta(scope.row)"
            v-hasPermi="['product:prod:remove']"
            >附件</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleShowProd(scope.row)"
            v-hasPermi="['product:prod:remove']"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="SPU" prop="prodSpu">
          <el-input v-model="form.prodSpu" placeholder="请输入SPU" />
        </el-form-item>
        <el-form-item label="商品类型" prop="prodKind">
          <el-radio-group v-model="form.prodKind">
            <el-radio
              v-for="dict in dict.type.sys_product_kind"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品分类" prop="prodType">
          <el-cascader
            v-model="form.prodType"
            :options="typeList"
            :props="cascaderProps"
            :show-all-levels="false"
            placeholder="请选择"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="form.prodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择商品单位">
            <el-option
              v-for="dict in dict.type.sys_product_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品标签" prop="tagId">
          <el-select v-model="form.tagId" placeholder="请选择商品标签">
            <el-option
              v-for="dict in dict.type.sys_product_tag"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="appr">
          <el-input v-model="form.appr" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择">
            <el-option
              v-for="item in brandList"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="appr">
          <el-radio-group v-model="form.prodStatus">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">备选项</el-radio>
            <el-radio :label="3">售罄</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="缩略图" prop="prodImage">
          <image-upload v-model="form.prodImage" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 附件添加 -->
    <div>
      <el-dialog title="附件添加" :visible.sync="dialogAttaFormVisible">
        <el-form :model="attaForm">
          <el-form-item label="轮播图" :label-width="formLabelWidth">
            <image-upload v-model="attaForm.attaImages" />
          </el-form-item>
          <el-form-item label="视频" :label-width="formLabelWidth">
            <file-upload v-model="attaForm.attaVideo" />
          </el-form-item>
          <el-form-item label="上架" :label-width="formLabelWidth">
            <el-radio-group v-model="attaForm.upFlag">
              <el-radio :label="0">立即上架</el-radio>
              <el-radio :label="1">定时下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.upFlag == 1"
              v-model="attaForm.upTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="下架" :label-width="formLabelWidth">
            <el-switch
              v-model="attaForm.downFlag"
              active-text="定时下架"
              inactive-text="立即下架"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.downFlag == 1"
              v-model="attaForm.downTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveProdAtta()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 详情 -->
    <div>
      <el-dialog title="详情" :visible.sync="dialogInfoFormVisible">
        <el-form :model="form">
          <el-descriptions title="商品信息">
            <el-descriptions-item label="商品Id">{{
              form.prodId
            }}</el-descriptions-item>
            <el-descriptions-item label="商品名称">{{
              form.prodName
            }}</el-descriptions-item>
            <el-descriptions-item label="SPU">{{
              form.prodSpu
            }}</el-descriptions-item>
            <el-descriptions-item label="图片">
              <el-image
                style="width: 50px; height: 50px"
                :src="form.prodImage"
              ></el-image>
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">{{
              form.createTime
            }}</el-descriptions-item>
          </el-descriptions>
        </el-form>
        <el-button type="primary" @click="onAddProdInfo">添加SKU</el-button>
        <div>
          <el-table :data="prodInfo" style="width: 100%">
            <el-table-column prop="infoId" label="ID" width="180">
            </el-table-column>
            <el-table-column prop="prodSku" label="SKU" width="180">
            </el-table-column>
            <el-table-column prop="prodName" label="商品名称">
            </el-table-column>
            <el-table-column prop="prodPrice" label="售价"> </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
          </el-table>
          <!-- 添加分页 -->
          <pagination
            v-show="prodInfoTotal > 0"
            :total="prodInfoTotal"
            :page.sync="prodInfoQueryParams.pageNum"
            :limit.sync="prodInfoQueryParams.pageSize"
            @pagination="getProdInfoList"
          />
        </div>
        <!-- 商品信息添加 -->
        <div>
          <el-dialog
            title="商品信息添加"
            :visible.sync="dialogAddInfoFormVisible"
          >
            <el-form :model="infoForm">
              <el-form-item label="SKU" :label-width="formLabelWidth">
                <el-input
                  v-model="infoForm.prodSku"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input
                  v-model="infoForm.prodName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="售价" :label-width="formLabelWidth">
                <el-input
                  v-model="infoForm.prodPrice"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="成本价" :label-width="formLabelWidth">
                <el-input
                  v-model="infoForm.costPrice"
                  autocomplete="off"
                ></el-input>
              </el-form-item>

              <el-form-item label="库存" :label-width="formLabelWidth">
                <el-input
                  v-model="infoForm.prodStock"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveProdInfo()"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
        <div slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogInfoFormVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="dialogInfoFormVisible = false"
            >关闭</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listProd,
  getProd,
  delProd,
  addProd,
  updateProd,
  addProdAtta,
  getProdInfo,
  addProdInfo,
  getProdListByEs,
} from "@/api/product/prod";
import { listType } from "@/api/product/type";
import { listBrand } from "@/api/product/brand";
export default {
  name: "Prod",
  dicts: ["sys_product_tag", "sys_product_unit", "sys_product_kind"],
  data() {
    return {
      // ...其他变量
      prodInfoQueryParams: {
        // SKU查询参数
        pageNum: 1,
        pageSize: 4, // 每页显示数量
        prodId: null, // 商品ID
      },
      prodInfoTotal: 0, // SKU总数

      dialogAttaFormVisible: false,
      dialogInfoFormVisible: false,
      dialogAddInfoFormVisible: false,
      formLabelWidth: "120px",
      attaForm: {},
      infoForm: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品列表表格数据
      prodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 4,
        prodName: null,
      },
      //SkU信息
      prodInfo: [],
      //品牌下拉框
      brandList: [],
      // 表单参数
      form: {},
      //商品分类数组
      typeList: [],
      cascaderProps: {
        value: "typeId",
        label: "typeName",
        children: "children",
        checkStrictly: true,
        emitPath: false,
      },
      // 表单校验
      rules: {
        prodSpu: [{ required: true, message: "SPU不能为空", trigger: "blur" }],
        prodKind: [
          { required: true, message: "商品类型不能为空", trigger: "change" },
        ],
        prodType: [
          { required: true, message: "商品分类不能为空", trigger: "change" },
        ],
        prodType: [
          { required: true, message: "商品分类不能为空", trigger: "change" },
        ],
        prodStatus: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "change" },
        ],
        unitId: [
          { required: true, message: "商品单位不能为空", trigger: "change" },
        ],
        tagId: [
          { required: true, message: "商品标签不能为空", trigger: "change" },
        ],
        appr: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    //获取商品列表
    this.getList();
    //获取分了级联下拉框
    this.getTypeTreeList();
    //获取品牌下拉框
    this.getBrandList();
    //商品信息
    this.getProdInfoList();
  },
  methods: {
    /** 保存附件 */
    saveProdAtta() {
      addProdAtta(this.attaForm).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("修改成功");
          this.dialogAttaFormVisible = false;
          this.getProdInfoList();
        } else {
          this.$modal.msgError(response.msg);
        }
      });
    },

    onAddProdInfo() {
      this.dialogAddInfoFormVisible = true;
    },
    handleAddAtta(row) {
      console.log("row", row);
      this.attaForm.prodId = row.prodId;
      this.dialogAttaFormVisible = true;
    },
    handleShowProd(row) {
      // this.form.prodId = row;
      const prodId = row.prodId || this.ids;
      getProd(prodId).then((response) => {
        this.form = response.data;
      });
      this.dialogInfoFormVisible = true;
      this.infoForm.prodId = prodId;

      // 初始化查询参数
      this.prodInfoQueryParams.prodId = prodId;
      // this.prodInfoQueryParams.pageNum = 1;

      // this.getProdInfoList();
    },
    /** 保存SKU */
    saveProdInfo() {
      addProdInfo(this.infoForm).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("添加成功");
          this.dialogAddInfoFormVisible = false;
          this.getProdInfoList(); // 重新获取商品信息列表
        } else {
          this.$modal.msgError(response.msg);
        }
      });
    },
    /** 获取SKU列表 */
    getProdInfoList() {
      getProdInfo(this.prodInfoQueryParams).then((response) => {
        console.log("info----------", response);

        console.log("返回数据条数:", response.rows.length); // 应该是 3
        this.prodInfo = response.rows;
        this.prodInfoTotal = response.total;
      });
    },
    /** 查询品牌列表列表 */
    getBrandList() {
      let param = {
        pageNum: 1,
        pageSize: 99999,
      };
      listBrand(param).then((response) => {
        this.brandList = response.rows;
      });
    },

    /** 查询商品分类列表列表 */
    getTypeTreeList() {
      let paramType = {
        pageNum: 1,
        pageSize: 99999,
      };
      listType(paramType).then((response) => {
        this.typeList = this.handleTree(response.data, "typeId", "typePid");
        this.loading = false;
      });
    },
    /** 查询商品列表列表 */
    getList() {
      this.loading = true;
      getProdListByEs(this.queryParams).then((response) => {
        this.prodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        prodId: null,
        prodSpu: null,
        prodKind: null,
        prodType: null,
        prodStatus: null,
        prodName: null,
        brandId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        unitId: null,
        tagId: null,
        appr: null,
        prodImage: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.prodId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prodId = row.prodId || this.ids;
      getProd(prodId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.prodId != null) {
            updateProd(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prodIds = row.prodId || this.ids;
      this.$modal
        .confirm('是否确认删除商品列表编号为"' + prodIds + '"的数据项？')
        .then(function () {
          return delProd(prodIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/prod/export",
        {
          ...this.queryParams,
        },
        `prod_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
